import cloud from '@lafjs/cloud'
let ctxParams
let dbName = "dict"

export default async function (ctx: FunctionContext) {
  ctxParams = ctx.body
  switch (ctx.body.type) {
    case "list":
      return listFunc()
      break;
    case "add":
      return addFunc()
      break;
    case "update":
      return updateFunc()
      break;
    case "delete":
      return delFunc()
      break;
    case "details":
      return detailsFunc()
      break;
    case "query":
      return queryFunc()
      break;
    default:
      break;
  }
  return { data: 'hi, laf' }
}

async function detailsFunc() {
  let res = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: { ...ctxParams.data }
  });
  return cloud.utils.requestReturn({ data: res })
}

async function listFunc() {
  let dataJson = { ...ctxParams.data }
  delete dataJson.pageIndex
  delete dataJson.pageSize
  let query = cloud.utils.extractValidKeys(dataJson)
  let res = await cloud.nw.db.select({
    dbName,
    getCount: true,
    pageIndex: ctxParams.pageIndex,
    pageSize: ctxParams.pageSize,
    whereJson: query,
  });
  return cloud.utils.requestReturn({ data: res })
}


async function addFunc() {
  let dataJson = { ...ctxParams.data }
  delete dataJson.type
  if (dataJson.hasOwnProperty("_id")) delete dataJson._id
  dataJson._add_time = Date.now()
  await cloud.nw.db.add({
    dbName, dataJson, cancelAddTime: true
  });
  return cloud.utils.requestReturn({ data: "" })
}

async function updateFunc() {
  let dataJson = { ...ctxParams.data }
  delete dataJson.type
  if (dataJson.hasOwnProperty("_id")) delete dataJson._id
  dataJson._update_time = Date.now()
  await cloud.nw.db.update({
    dbName, dataJson, whereJson: { _id: ctxParams.data._id }
  });
  return cloud.utils.requestReturn({ data: "" })
}

async function delFunc() {
  await cloud.nw.db.del({
    dbName,
    whereJson: {
      _id: ctxParams.data._id
    }
  });
  return cloud.utils.requestReturn({ data: "" })
}

async function queryFunc() {
  let dataJson = { ...ctxParams.data }
  delete dataJson.type
  let query = cloud.utils.extractValidKeys(dataJson)
  let data = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: query
  });
  return cloud.utils.requestReturn({ data: data.data })
}